package practica_CDLibrary;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class ConnexioOk {
	
	private static Properties props = initProps();	
	private static Connection conn;

	public Connection openConnexio(){
		
		conn = null;
		try {
			
			String driverEspecific = getPropietat("rdbms.driver");
			Class.forName(driverEspecific).newInstance();
			
			conn = DriverManager
				.getConnection(
						getPropietat("rdbms.url"),
						getPropietat("rdbms.usuario"), 
						getPropietat("rdbms.pwd"));
			
			mostrarInfoMetadata(conn);			
			
			
			return conn;
			
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			
			e.printStackTrace();
			
		} catch (SQLException e) {			
			e.printStackTrace();
		} 
		return conn;
		
	}
	
	public void closeConnexio(Connection conn){
	
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {					
					e.printStackTrace();
				}
			}
		}	
	
	public Statement getStatement() {
		
		Statement st = null;
		try {
			st = conn.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return st;
	}
	private static void mostrarInfoMetadata(Connection conn) {
		try {
			DatabaseMetaData dbmd = conn.getMetaData();
			
			
			ResultSet rs = dbmd.getCatalogs();			
			while (rs.next()) {
				System.out.println("-" + rs.getString(1));
			}			
		} catch (SQLException e) {			
			e.printStackTrace();
		}
		
	}

	private static Properties initProps() {
		
		String nomPropertiesFileDb =
				System.getProperty("propFileDbName");
		
		InputStream is = 
			ConnexioOk.class.getResourceAsStream("/"+nomPropertiesFileDb);
			
		props = new Properties();
		try {
			props.load(is);
			return props;
		} catch (IOException e) {			
			e.printStackTrace();
		}
		throw new RuntimeException("Error cargando fichero de propiedades de la BD!");
	}

	private static String getPropietat(String propiedad) {
		return props.getProperty(propiedad);
	}

}
